package openAbility

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"gitee.com/yizhisamoye/GoWeChat/entity"
)

type EncryptedData struct {
	Iv string `json:"iv"`
	ErrMsg string `json:"errMsg"`
	EncryptedData string `json:"encryptedData"`
}
func (e EncryptedData)DecryptData(appId,sessionKey string)(map[string]interface{},error){
	if len(sessionKey)!=24{
		return nil,entity.NewWxErr(41001,"sessionKey 不合法",0)
	}
	aesKeyByte,err:=base64.StdEncoding.DecodeString(sessionKey)
	if err!=nil{
		return nil,err
	}
	if len(e.Iv)!=24{
		return nil,entity.NewWxErr(41002,"iv 不合法",0)
	}
	aesIvByte,err:=base64.StdEncoding.DecodeString(e.Iv)
	if err!=nil{
		return nil,err
	}
	aesCipherByte,err:=base64.StdEncoding.DecodeString(e.EncryptedData)
	dataBytes, err := aesDecrypt(aesCipherByte, aesKeyByte, aesIvByte)
	if err!=nil{
		return nil,entity.NewWxErr(41003,"aes解密未成功",0)
	}
	m := make(map[string]interface{})
	err = json.Unmarshal(dataBytes, &m)
	if err != nil {
		return nil, err
	}
	temp := m["watermark"].(map[string]interface{})
	tempAppId := temp["appid"].(string)
	if tempAppId != appId{
		return nil, entity.NewWxErr(41003,"aes解密未成功",0)
	}
	return m,nil
}
func aesDecrypt(crypted, key, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	//blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	//获取的数据尾端有'/x0e'占位符,去除它
	for i, ch := range origData {
		if ch == '\x0e' {
			origData[i] = ' '
		}
	}
	//{"phoneNumber":"15082726017","purePhoneNumber":"15082726017","countryCode":"86","watermark":{"timestamp":1539657521,"appid":"wx4c6c3ed14736228c"}}//<nil>
	return origData, nil
}